<template>
	<view class="real-map-container">
		<!-- 定位状态显示 -->
		<view class="location-status">
			<view class="status-item">
				<uni-icons :type="currentLocation ? 'location-filled' : 'location'" size="16" :color="currentLocation ? '#007AFF' : '#999'"></uni-icons>
				<text class="status-text">{{ currentLocation ? '已定位' : '未定位' }}</text>
			</view>
			<view class="status-item" v-if="currentLocation">
				<text class="status-text">{{ currentLocation.latitude.toFixed(6) }}, {{ currentLocation.longitude.toFixed(6) }}</text>
			</view>
			<view class="status-item">
				<text class="status-text">加油站数量：{{ gasStations.length }}个</text>
			</view>
		</view>
		
		<!-- 地图组件 -->
		<!-- #ifdef H5 -->
		<!-- H5端使用iframe显示高德地图 -->
		<view class="h5-map-container">
			<iframe 
				:src="h5MapUrl" 
				class="h5-map-iframe"
				frameborder="0"
				scrolling="no"
			></iframe>
		</view>
		<!-- #endif -->
		
		<!-- #ifndef H5 -->
		<!-- 其他平台使用原生地图组件 -->
		<map 
			class="real-map"
			:latitude="mapCenter.latitude"
			:longitude="mapCenter.longitude"
			:scale="mapScale"
			:markers="mapMarkers"
			:show-location="true"
			:enable-zoom="true"
			:enable-scroll="true"
			:enable-rotate="false"
			:enable-3D="false"
			@markertap="onMarkerTap"
			@regionchange="onRegionChange"
			@tap="onMapTap"
		></map>
		<!-- #endif -->
		
		<!-- 地图控制按钮 -->
		<view class="map-controls">
			<view class="control-btn" @click="zoomIn">
				<uni-icons type="plus" size="16" color="#333"></uni-icons>
			</view>
			<view class="control-btn" @click="zoomOut">
				<uni-icons type="minus" size="16" color="#333"></uni-icons>
			</view>
			<view class="control-btn" @click="moveToCurrentLocation">
				<uni-icons type="location-filled" size="16" color="#007AFF"></uni-icons>
			</view>
			<view class="control-btn" @click="addTestMarkers">
				<uni-icons type="star" size="16" color="#FFD700"></uni-icons>
			</view>
			<!-- #ifdef H5 -->
			<view class="control-btn" @click="openH5Map">
				<uni-icons type="map" size="16" color="#007AFF"></uni-icons>
			</view>
			<!-- #endif -->
		</view>
		
		<!-- 地图上的加油站详情卡片 -->
		<view v-if="selectedStation" class="station-card">
			<view class="card-content">
				<view class="station-image">
					<image :src="selectedStation.image" mode="aspectFill" class="station-img"></image>
				</view>
				<view class="station-info">
					<view class="station-name">{{ selectedStation.name }}</view>
					<view class="station-price">¥{{ selectedStation.price }}/升</view>
					<view class="station-address">{{ selectedStation.address }}</view>
					<view class="station-distance">{{ selectedStation.distance }}</view>
				</view>
				<view class="card-action">
					<text class="detail-link" @click="goToStationDetail(selectedStation)">详情》</text>
				</view>
			</view>
			<view class="navigation-button" @click="navigateToStation(selectedStation)">
				<text class="nav-text">立即导航</text>
			</view>
		</view>
	</view>
</template>

<script>
	import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
	
	export default {
		components: { 
			uniIcons
		},
		props: {
			currentLocation: {
				type: Object,
				default: null
			},
			gasStations: {
				type: Array,
				default: () => []
			}
		},
		data() {
			return {
				mapCenter: {
					latitude: 39.9042,
					longitude: 116.4074
				},
				mapScale: 13,
				mapMarkers: [],
				selectedStation: null,
				h5MapUrl: '' // H5端地图URL
			};
		},
		mounted() {
			console.log('RealMap组件已挂载');
			console.log('当前环境:', process.env.NODE_ENV);
			console.log('当前平台:', uni.getSystemInfoSync().platform);
			this.initMap();
		},
		watch: {
			currentLocation: {
				handler(newLocation) {
					if (newLocation) {
						console.log('位置更新:', newLocation);
						this.mapCenter = {
							latitude: newLocation.latitude,
							longitude: newLocation.longitude
						};
						this.updateH5MapUrl();
						this.updateMapMarkers();
					}
				},
				immediate: true
			},
			gasStations: {
				handler(newStations) {
					console.log('加油站数据更新:', newStations.length, '个');
					this.updateMapMarkers();
				},
				immediate: true,
				deep: true
			}
		},
		methods: {
			// 初始化地图
			initMap() {
				console.log('初始化地图组件');
				console.log('当前位置:', this.currentLocation);
				console.log('加油站数据:', this.gasStations);
				
				if (this.currentLocation) {
					this.mapCenter = {
						latitude: this.currentLocation.latitude,
						longitude: this.currentLocation.longitude
					};
					console.log('设置地图中心:', this.mapCenter);
				} else {
					console.log('使用默认地图中心:', this.mapCenter);
				}
				
				// 更新H5地图URL
				this.updateH5MapUrl();
				
				if (this.gasStations.length > 0) {
					console.log('有加油站数据，更新标记');
					this.updateMapMarkers();
				} else {
					console.log('暂无加油站数据');
				}
			},
			
			// 更新H5地图URL
			updateH5MapUrl() {
				// #ifdef H5
				const lat = this.mapCenter.latitude;
				const lng = this.mapCenter.longitude;
				const zoom = this.mapScale;
				
				// 构建高德地图URL
				this.h5MapUrl = `https://uri.amap.com/marker?position=${lng},${lat}&name=当前位置&src=mypage&coordinate=gaode&zoom=${zoom}`;
				console.log('H5地图URL:', this.h5MapUrl);
				// #endif
			},
			
			// 更新地图标记
			updateMapMarkers() {
				console.log('开始更新地图标记...');
				console.log('加油站数据:', this.gasStations);
				console.log('加油站数量:', this.gasStations ? this.gasStations.length : 0);
				
				if (!this.gasStations || this.gasStations.length === 0) {
					console.log('没有加油站数据，清空标记');
					this.mapMarkers = [];
					return;
				}
				
				// 确保每个加油站都有有效的坐标
				const validStations = this.gasStations.filter(station => {
					const isValid = station.latitude && station.longitude && 
						!isNaN(station.latitude) && !isNaN(station.longitude);
					if (!isValid) {
						console.warn('无效的加油站坐标:', station);
					}
					return isValid;
				});
				
				console.log('有效加油站数量:', validStations.length);
				
				this.mapMarkers = validStations.map((station, index) => {
					const marker = {
						id: index,
						latitude: parseFloat(station.latitude),
						longitude: parseFloat(station.longitude),
						title: station.name || `加油站${index + 1}`,
						iconPath: '/static/c1.png',
						width: 40,
						height: 40,
						callout: {
							content: `${station.name || '加油站'}\n¥${station.price || '0.00'}/升\n${station.distance || '未知距离'}`,
							color: '#333333',
							fontSize: 12,
							borderRadius: 6,
							bgColor: '#ffffff',
							padding: 10,
							display: 'ALWAYS',
							textAlign: 'center',
							borderWidth: 1,
							borderColor: '#e0e0e0'
						}
					};
					
					console.log(`创建标记 ${index}:`, {
						id: marker.id,
						latitude: marker.latitude,
						longitude: marker.longitude,
						title: marker.title
					});
					return marker;
				});
				
				console.log('最终地图标记数量:', this.mapMarkers.length);
				console.log('地图标记详情:', this.mapMarkers);
				
				// 调整地图缩放级别
				if (this.mapMarkers.length > 0) {
					this.adjustMapScale();
				}
			},
			
			// 调整地图缩放级别
			adjustMapScale() {
				if (this.gasStations.length === 0) return;
				
				const lats = this.gasStations.map(s => s.latitude);
				const lngs = this.gasStations.map(s => s.longitude);
				
				const minLat = Math.min(...lats);
				const maxLat = Math.max(...lats);
				const minLng = Math.min(...lngs);
				const maxLng = Math.max(...lngs);
				
				const latDiff = maxLat - minLat;
				const lngDiff = maxLng - minLng;
				const maxDiff = Math.max(latDiff, lngDiff);
				
				if (maxDiff > 0.01) {
					this.mapScale = 12;
				} else if (maxDiff > 0.005) {
					this.mapScale = 13;
				} else {
					this.mapScale = 14;
				}
				
				this.mapCenter = {
					latitude: (minLat + maxLat) / 2,
					longitude: (minLng + maxLng) / 2
				};
			},
			
			// 地图标记点击事件
			onMarkerTap(e) {
				const markerId = e.markerId;
				const station = this.gasStations[markerId];
				if (station) {
					this.selectedStation = station;
					console.log('点击了加油站:', station.name);
				}
			},
			
			// 地图点击事件
			onMapTap(e) {
				this.selectedStation = null;
			},
			
			// 地图区域变化事件
			onRegionChange(e) {
				if (e.type === 'end' && e.detail) {
					console.log('地图区域变化:', e.detail);
				}
			},
			
			// 地图缩放
			zoomIn() {
				if (this.mapScale < 20) {
					this.mapScale += 2;
				}
			},
			
			zoomOut() {
				if (this.mapScale > 8) {
					this.mapScale -= 2;
				}
			},
			
			// 移动到当前位置
			moveToCurrentLocation() {
				if (this.currentLocation) {
					this.mapCenter = {
						latitude: this.currentLocation.latitude,
						longitude: this.currentLocation.longitude
					};
					this.mapScale = 14;
					this.updateMapMarkers();
					
					uni.showToast({
						title: '已移动到当前位置',
						icon: 'success'
					});
				} else {
					this.$emit('request-location');
				}
			},
			
			// 跳转到加油站详情页
			goToStationDetail(station) {
				if (station) {
					uni.navigateTo({
						url: `/pages/Fuel Nearby/GasStationDetail?id=${station.id}`
					});
				}
			},
			
			// 导航到加油站
			navigateToStation(station) {
				if (!station) return;
				
				// #ifdef MP-WEIXIN
				uni.openLocation({
					latitude: station.latitude,
					longitude: station.longitude,
					name: station.name,
					address: station.address,
					scale: 18
				});
				// #endif
				
				// #ifdef H5
				const mapUrl = `https://uri.amap.com/navigation?to=${station.longitude},${station.latitude},${station.name}&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0`;
				window.open(mapUrl, '_blank');
				// #endif
				
				// #ifdef APP-PLUS
				uni.openLocation({
					latitude: station.latitude,
					longitude: station.longitude,
					name: station.name,
					address: station.address,
					scale: 18
				});
				// #endif
			},

			// 打开H5地图
			openH5Map() {
				// #ifdef H5
				if (this.h5MapUrl) {
					window.open(this.h5MapUrl, '_blank');
				}
				// #endif
			},
			
			// 添加测试标记
			addTestMarkers() {
				console.log('添加测试标记');
				const testMarkers = [
					{
						id: 'test1',
						latitude: 39.9042 + 0.001,
						longitude: 116.4074 + 0.001,
						title: '测试标记1',
						iconPath: '/static/c1.png',
						width: 40,
						height: 40,
						callout: {
							content: '测试标记1\n¥0.00/升\n未知距离',
							color: '#333333',
							fontSize: 12,
							borderRadius: 6,
							bgColor: '#ffffff',
							padding: 10,
							display: 'ALWAYS',
							textAlign: 'center',
							borderWidth: 1,
							borderColor: '#e0e0e0'
						}
					},
					{
						id: 'test2',
						latitude: 39.9042 - 0.001,
						longitude: 116.4074 - 0.001,
						title: '测试标记2',
						iconPath: '/static/c2.png',
						width: 40,
						height: 40,
						callout: {
							content: '测试标记2\n¥0.00/升\n未知距离',
							color: '#333333',
							fontSize: 12,
							borderRadius: 6,
							bgColor: '#ffffff',
							padding: 10,
							display: 'ALWAYS',
							textAlign: 'center',
							borderWidth: 1,
							borderColor: '#e0e0e0'
						}
					}
				];
				this.mapMarkers = [...this.mapMarkers, ...testMarkers];
				console.log('当前地图标记数量:', this.mapMarkers.length);
				this.adjustMapScale();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.real-map-container {
		position: relative;
		height: calc(100vh - 200px);
		
		.location-status {
			position: absolute;
			top: 16px;
			left: 16px;
			right: 16px;
			background-color: rgba(255, 255, 255, 0.9);
			border-radius: 8px;
			padding: 12px;
			z-index: 10;
			
			.status-item {
				display: flex;
				align-items: center;
				gap: 8px;
				margin-bottom: 4px;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				.status-text {
					font-size: 12px;
					color: #666666;
				}
			}
		}
		
		.real-map {
			width: 100%;
			height: 100%;
		}

		.h5-map-container {
			width: 100%;
			height: 100%;
			position: relative;

			.h5-map-iframe {
				width: 100%;
				height: 100%;
				border: none;
			}
		}
		
		.map-controls {
			position: absolute;
			right: 16px;
			bottom: 100px;
			display: flex;
			flex-direction: column;
			gap: 8px;
			z-index: 10;
			
			.control-btn {
				width: 40px;
				height: 40px;
				background-color: #ffffff;
				border-radius: 8px;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
			}
		}
		
		.station-card {
			position: absolute;
			bottom: 20px;
			left: 16px;
			right: 16px;
			background-color: #ffffff;
			border-radius: 12px;
			padding: 16px;
			box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
			z-index: 10;
			
			.card-content {
				display: flex;
				align-items: center;
				margin-bottom: 12px;
				
				.station-image {
					width: 60px;
					height: 45px;
					margin-right: 12px;
					
					.station-img {
						width: 100%;
						height: 100%;
						border-radius: 8px;
					}
				}
				
				.station-info {
					flex: 1;
					
					.station-name {
						font-size: 16px;
						font-weight: bold;
						color: #333333;
						margin-bottom: 4px;
					}
					
					.station-price {
						font-size: 14px;
						color: #ff4757;
						font-weight: bold;
						margin-bottom: 4px;
					}
					
					.station-address {
						font-size: 12px;
						color: #666666;
						margin-bottom: 4px;
					}
					
					.station-distance {
						font-size: 12px;
						color: #007AFF;
					}
				}
				
				.card-action {
					.detail-link {
						font-size: 14px;
						color: #007AFF;
					}
				}
			}
			
			.navigation-button {
				background-color: #007AFF;
				padding: 12px;
				border-radius: 8px;
				text-align: center;
				
				.nav-text {
					color: #ffffff;
					font-size: 16px;
					font-weight: bold;
				}
			}
		}
	}
</style> 